﻿#region [===== Using =====]
using System;
#endregion

namespace TPG.SharePoint.Workflow
{
    /// <summary>
    /// A control for configuring a workflow during workflow association and 
    /// instantiation which can be hosted inside a page using the hosted 
    /// control framework.
    /// </summary>
    public abstract class ConfigurationControl
         : WorkflowDataControl<ConfigurationData, ConfigurationMetaData>
    {
        #region [===== Properties =====]
        /// <summary>
        /// Gets the <see cref="AssociationType" /> indicating with 
        /// what type of content the workflow is associated.
        /// </summary>
        protected AssociationType AssociationType
        {
            get { return MetaData.AssociationType; }
        }

        /// <summary>
        /// Getst the name of the target with which the workflow is 
        /// associated.
        /// </summary>
        protected string AssociationTargetName
        {
            get { return MetaData.AssociationTargetName; }
        }
        #endregion

        #region [===== Protected methods =====]
        /// <summary>
        /// Gets the configuration data as a typed object, automatically 
        /// deserializing the data from a string.
        /// </summary>
        /// <typeparam name="TData">The Type of data to use.</typeparam>
        /// <returns>The typed data.</returns>
        protected TData GetDataAs<TData>()
            where TData : class
        {
            ConfigurationData data = GetData();
            return data.GetTypedData<TData>(GetSerializationModeForLoad());
        }

        /// <summary>
        /// Saves the configuration data as a typed object, automatically
        /// serializing the data to a string.
        /// </summary>
        /// <typeparam name="TData">The Type of data to use.</typeparam>
        /// <param name="data">The typed object</param>
        /// <returns>A <see cref="ConfigurationData" /> object containing the 
        /// data in serialized form.</returns>
        protected ConfigurationData SaveDataAs<TData>(TData data)
            where TData : class
        {
            return ConfigurationData.CreateUsingTypedData<TData>(data, SerializationMode);
        }
        #endregion

        #region [===== Private methods =====]
        SerializationMode GetSerializationModeForLoad()
        {
            SerializationMode mode = SerializationMode;
            if (PageType == PageType.Instantiation)
            {
              SerializationMode? associationMode = WorkflowConfiguration.GetSerializationMode(
                WorkflowPage.WorkflowTemplate,
                PageType.Association);
              if (associationMode != null)
              {
                mode = associationMode.Value;
              }
            }
            return mode;
        }
        #endregion
    }
}
